package com.microframework.boot.datarule.service.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.microframework.base.core.dbconfig.DbConfigUtil;
import com.microframework.base.web.page.PageQuery;
import com.microframework.boot.datarule.model.domain.DbConfig;
import com.microframework.boot.datarule.service.IDbConfigService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DbConfigServiceImpl implements IDbConfigService {

	@Override
	public List<DbConfig> loadAll(PageQuery<DbConfig> pageQuery) {
		try {
			String select = "select * ";
			StringBuilder sqlBuilder = new StringBuilder(select + " FROM " + DbConfig.TABLE_NAME + " WHERE 1=1");
			List<Object> params = new ArrayList<>();

			DbConfig query = pageQuery.getQuery();
			if (query != null) {
				// 构建查询条件

				if (StringUtils.hasText(query.getName())) {
					sqlBuilder.append(" AND name LIKE ?");
					params.add("%" + query.getName() + "%");
				}

				if (StringUtils.hasText(query.getIsDel())) {
					sqlBuilder.append(" AND is_del = ?");
					params.add(query.getIsDel());
				} else {
					sqlBuilder.append(" AND is_del = ?");
					params.add("0");
				}
			}else {
				sqlBuilder.append(" AND is_del = ?");
				params.add("0");
			}

			// 设置排序
			String orderBy = StringUtils.hasText(pageQuery.getOrderBy()) ? pageQuery.getOrderBy() : " modify_time";
			String orderDirection = StringUtils.hasText(pageQuery.getOrderDirection()) ? pageQuery.getOrderDirection()
					: "desc";
			sqlBuilder.append(" ORDER BY " + orderBy + " " + orderDirection);
			List<DbConfig> list=DbConfig.dao.find(sqlBuilder.toString(), params.toArray());
			
			for(DbConfig dbConfig:list) {
				dbConfig.setStatus(DbConfigUtil.isActive(dbConfig.getId())?"0":"1");
			}
			return list;
		} catch (Exception e) {
			log.error("查询异常{}", e.getMessage());
			return new LinkedList<DbConfig>();
		}
	}

}
